package com.wwu.config;

import com.wwu.common.ComConst;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.saaj.SAAJInInterceptor;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.w3c.dom.NodeList;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;

/**
 * 服务权限拦截器
 * @Author: 一蓑烟雨
 * @CreateTime: 2021-10-30 20:49
 * @Version: 1.0.0
 **/
@Slf4j
@Component
@ConfigurationProperties(prefix = "webservice")
public class ServiceAuthInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
    /** 注入webservice账号密码 */
    @Setter
    private String[] auths;
    /** 拦截器 */
    private SAAJInInterceptor saaj =new SAAJInInterceptor();

    /**
     *  构造方法
     * @Author: 一蓑烟雨
     * @Date: 2021/10/30 0030 下午 21:06
     */
    public ServiceAuthInterceptor() {
        super(Phase.PRE_PROTOCOL);
        super.getAfter().add(SAAJInInterceptor.class.getName());
    }


    /**
     * 判断客户端调用时传的用户名和密码是否正确
     * @Author: 一蓑烟雨
     * @Date: 2021/10/30 0030 下午 21:06
     */
    @Override
    public void handleMessage(SoapMessage soapMessage) throws Fault {
        SOAPMessage message = soapMessage.getContent(SOAPMessage.class);
        if(message == null){
            this.saaj.handleMessage(soapMessage);
            message = soapMessage.getContent(SOAPMessage.class);
        }
        SOAPHeader header = null;
        try {
            header = message.getSOAPHeader();
        }catch (Exception e){
            e.printStackTrace();
        }

        if(header == null){
            throw  new Fault(new IllegalAccessException("找不到Header信息，认证失败"));
        }
        //获取用户名和密码节点信息
        NodeList usernameEle = header.getElementsByTagName("username");
        NodeList passwordEle = header.getElementsByTagName("password");
        if(usernameEle.getLength()<1){
            throw  new Fault(new IllegalAccessException("找不到username信息，认证失败"));
        }
        if(passwordEle.getLength()<1){
            throw  new Fault(new IllegalAccessException("找不到password信息，认证失败"));
        }
        //获取前端传的用户名和密码
        String username = usernameEle.item(0).getTextContent().trim();
        String password = passwordEle.item(0).getTextContent().trim();

        Boolean authFlag = false;
        //遍历账号密码
        for (String auth : this.auths) {
            if(username.equals(auth.split(ComConst.SPLIT_SX)[0]) && password.equals(auth.split(ComConst.SPLIT_SX)[1])){
                authFlag = true;
                log.debug("认证成功");
                break;
            }
        }
        //认证失败
        if(!authFlag){
            throw  new Fault(new SOAPException("用户名或密码错误，认证失败"));
        }
    }
}
